package stephen.com.controller.user;

import stephen.com.controller.BaseServlet;
import stephen.com.model.UserFocus;
import stephen.com.service.UserService;
import stephen.com.service.impl.UserServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

@WebServlet("/users/*")
public class UserServlet extends BaseServlet {
	private UserService userService = new UserServiceImpl();

	public void userList(HttpServletRequest request, HttpServletResponse response) {
		try {
			//获取前端提交的数据
			String currentPage = request.getParameter("currentPage");
			//如果前端没有提交数据，那默认当前页就是第一页
			int page = 1;
			if ( null != currentPage ) {
				page = Integer.parseInt(currentPage);
			}
			String search = request.getParameter("search");
			if ( null != search ) {
				String encode = URLEncoder.encode(search, "UTF-8");
				response.sendRedirect(request.getContextPath() + "/view/user?page=" + page + "&search=" + encode);
			} else {
				response.sendRedirect(request.getContextPath() + "/view/user?page=" + page);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
		public void unFocus (HttpServletRequest request, HttpServletResponse response){
			try {
				response.setHeader("Content-Type", "text/html");
				String ufId = request.getParameter("ufId");
				if ( null != ufId ) {
					userService.unFocus(Integer.parseInt(ufId));
					response.getWriter().write("success");
				} else {
					response.getWriter().write("请传ufId");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		public void focus (HttpServletRequest request, HttpServletResponse response){
			try {
				response.setHeader("Content-Type", "text/html");
				String userFocusId = request.getParameter("uId");
				if ( null != userFocusId ) {
					String userId = request.getSession().getAttribute("userId").toString();
					if ( userId.equals(userFocusId) ) {
						//自己不能关注自己
						response.getWriter().write("不能关注自己");
					} else {
						//通过当前登录的用户Id 以及 要关注的用户ID(userFocusId) --> 然后去关注表查询有没有数据先
						UserFocus focus = userService.findOneFocusData(Integer.parseInt(userId),
								Integer.parseInt(userFocusId));
						if ( null == focus ) {
							//没有数据接下来才可以添加关注信息
							userService.focus(Integer.parseInt(userId), Integer.parseInt(userFocusId));
							response.getWriter().write("success");
						} else {
							response.getWriter().write("关注失败");
						}
					}
				} else {
					response.getWriter().write("关注失败");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}
